const Koa = require('koa');
const co = require('co')
const nunjucksViews = require('koa-nunjucks-promise')
const router = require('koa-router')
const mount = require('koa-mount')
const server = require('koa-static')
const request = require('superagent'); //不要忘记npm install

const koaBody = require('koa-body')();
const app = new Koa();
const route = new router();
var config=require('./config/app.config')
app.use(nunjucksViews(`${__dirname}/views`, { //配置模板文件路径，
    ext: 'html', //渲染文件后缀为 html
    noCache: process.env.NODE_ENV === 'development', //开发环境下不设置缓存
    watch: process.env.NODE_ENV === 'development', //开发环境下观察模板文件的变化并更新
    filters: { //过滤器  
        json: function(str) {
            return JSON.stringify(str, null, 2)
        }
    },
    globals: { //设置对于nunjucks的全局变量
        // staticPath: '//static'
    }
}))
app.use(mount('/static', server(`${__dirname}/public`))) //设置静态文件路径
route.get('/', co.wrap(function*(ctx) {
    yield ctx.render('index', { title: 'Nunjucks', content: 'Feifeiyu yeah!' })
}))
app.use(route.routes()).use(route.allowedMethods())

route.get('/route/test', co.wrap(function*(ctx) {
    ctx.body = 'feifeiyu nuaa'
}))


/**微信授权登陆完成重定向 
 * 1.获取授权code
 * 2、带上当前商户或平台的编号请求后台
 * 3、获取到微信授权用户信息重定向到首页进行缓存
 */
route.get('/weixin/getWxCode', co.wrap(function*(ctx) {

    // 调用远程接口获取用户授权信息
    request
        .post(config.host+'/weixin/getWxUser')
        .send({ code: 'Manny', merchantNo: 'wwew' })
        .set('X-API-Key', 'foobar')
        .set('Accept', 'application/json')
        .set('Content-Type', 'application/json')
        .end(function(err, res) {
            if (res.ok) {
                console.log('yay got ' + JSON.stringify(res.body));
                ctx.render('index', { title: 'Nunjucks', content: 'Feifeiyu yeah!' });
            } else {
                console.log('Oh no! error ' + err);
            }
        });

}))

const routers = require('./routers/index')

app.use(routers.routes()).use(routers.allowedMethods())



route.post('/weixin/invited', co.wrap(function*(ctx) {

    // 调用远程接口获取用户授权信息
    request
        .post(config.host+'/customer/invited')
        .send({ code: 'Manny', merchantNo: 'wwew' })
        .set('X-API-Key', 'foobar')
        .set('Accept', 'application/json')
        .set('Content-Type', 'application/json')
        .end(function(err, res) {
            if (res.ok) {
                console.log('yay got ' + JSON.stringify(res.body));
                ctx.render('index', { title: 'Nunjucks', content: 'Feifeiyu yeah!' });
            } else {
                console.log('Oh no! error ' + err);
            }
        });

}))
app.use(function *(){
    console.log(this.path);
    this.body = 'Hello World';
});

app.listen(3000);
